package com.zyasdk.view.view;

import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zhuoyian.analysis.Analysis;
import com.zhuoyian.analysis.AnalysisBuilder;
import com.zhuoyian.analysis.AnalysisBuilder.Click;
import com.zhuoyian.analysis.AnalysisBuilder.DownLoadState;
import com.zhuoyian.analysis.AnalysisBuilder.IsBreak;
import com.zhuoyian.analysis.AnalysisBuilder.OpenManner;
import com.zhuoyian.analysis.common.AnalysisConsts;
import com.zyasdk.controll.WindowUtil;
import com.zyasdk.enums.AdType;
import com.zyasdk.interfaces.OnDLImageSuccessListener;
import com.zyasdk.interfaces.OnProductDLListener;
import com.zyasdk.interfaces.OnStartUpDimissListener;
import com.zyasdk.model.Products;
import com.zyasdk.service.DLImage;
import com.zyasdk.util.AppInfoUtil;
import com.zyasdk.util.ZYALogUtils;
import com.zyasdk.util.ScreenUtils;
import com.zyasdk.util.Util;

public class ViewFactory {

	/**
	 * 获取普通广告视图
	 * 
	 * @param context
	 * @param d
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static View getAdView(final Context context, Drawable d,
			final Products ad,
			final OnProductDLListener touchListener) {
		boolean isScreenChange = Util.isScreenChange(context);
		LinearLayout layoutP = new LinearLayout(context);

		layoutP.setBackgroundColor(Util.ConvertColorToInt("50000000"));
		layoutP.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT));
		layoutP.setGravity(Gravity.CENTER);
		RelativeLayout layout = new RelativeLayout(context);
		layout.setAnimation(AnimationUtils.loadAnimation(context,
				android.R.anim.fade_in));

		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		int width = display.getWidth();
		int height = display.getHeight();
		ZYALogUtils.e("display--->w:" + width + "   h:" + height);
		// 横竖屏状态下计算方式不相同
		if (isScreenChange) {
			double beishu = (double) height / (double) width;
			height -= Util.dip2px(context, 20);
			layout.setLayoutParams(new RelativeLayout.LayoutParams(
					(int) (height * beishu), height));
		} else {
			double beishu = (double) (width) / (double) height;
			width -= Util.dip2px(context, 20);
			layout.setLayoutParams(new RelativeLayout.LayoutParams(
					(int) (width * beishu), width));
		}

		LinearLayout layout1 = new LinearLayout(context);
		Button btn = new Button(context);
		RelativeLayout.LayoutParams lap = new RelativeLayout.LayoutParams(
				Util.dip2px(context, 15), Util.dip2px(context, 15));
		lap.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 1);
		btn.setLayoutParams(lap);
		int margin = 5;
		lap.setMargins(0, Util.dip2px(context, margin),
				Util.dip2px(context, margin), 0);
		// 关闭
		btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				WindowUtil.getModel(context).hidePopupWindow();
			}
		});
		btn.setBackgroundDrawable(Util.getAssetsDrawable(context,
				"img/close.png"));

		lap = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.MATCH_PARENT,
				RelativeLayout.LayoutParams.MATCH_PARENT);
		ImageView iv = new ImageView(context);
		LinearLayout.LayoutParams lpa = new android.widget.LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		iv.setImageDrawable(d);
		iv.setScaleType(ScaleType.CENTER_CROP);
		iv.setLayoutParams(lpa);
		// 触摸图片进行下载
		iv.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (touchListener != null) {
					touchListener.onDownLoad(ad);
				}
				return false;
			}
		});
		layout1.setLayoutParams(lap);
		layout1.addView(iv);
		layout.addView(layout1);
		layout.addView(btn);
		layoutP.addView(layout);
		return layoutP;

	}

	/**
	 * 获取启动视图
	 * 
	 * @param icon
	 * @param view
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static View getStartUpView(final Context context, final int showSecond,
			int icon, View view, String appName, String about,final Products advert,OnStartUpDimissListener onStartUpDimissListener) {
		RelativeLayout layout = new RelativeLayout(context);

		layout.addView(view);

		LinearLayout layoutBottom = new LinearLayout(context);
		// --------设置底部视图背景
		layoutBottom.setBackgroundDrawable(Util.getAssetsDrawable(context,
				"img/bottom_bg.9.png"));

		// 底部视图（80dip）
		RelativeLayout.LayoutParams bottomLp = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.MATCH_PARENT, Util.dip2px(context,
						80));
		// 将视图放置在屏幕底部
		bottomLp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		layoutBottom.setLayoutParams(bottomLp);
		// 内部局左右两边间距10dip
		layoutBottom.setPadding(Util.dip2px(context, 10), 0,
				Util.dip2px(context, 10), 0);
		// 内部局横向
		layoutBottom.setOrientation(LinearLayout.HORIZONTAL);
		// 内部局纵向居中
		layoutBottom.setVerticalGravity(Gravity.CENTER_VERTICAL);
		// 应用Logo
		ImageView iconImage = new ImageView(context);
		// 将icon设置为背景图片
		iconImage.setBackgroundResource(icon);
		// Logo图片显示为60*60dip
		LinearLayout.LayoutParams blp = new LinearLayout.LayoutParams(
				Util.dip2px(context, 50), Util.dip2px(context, 50));
		// 右边间距10dip
		blp.setMargins(0, 01, Util.dip2px(context, 10), 0);
		iconImage.setLayoutParams(blp);
		// 将图标加入到底部视图
		layoutBottom.addView(iconImage);

		LinearLayout layoutBCenter = new LinearLayout(context);
		blp = new LinearLayout.LayoutParams(Util.dip2px(context, 60),
				LinearLayout.LayoutParams.MATCH_PARENT);
		blp.weight = 1;
		layoutBCenter.setVerticalGravity(Gravity.CENTER_VERTICAL);
		layoutBCenter.setLayoutParams(blp);
		layoutBCenter.setOrientation(LinearLayout.VERTICAL);

		// 应用名
		TextView tvName = new TextView(context);
		tvName.setText(TextUtils.isEmpty(appName) ? AppInfoUtil
				.getApplicationName(context) : appName);
		// 字体大小18dip
		tvName.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
		tvName.setTextColor(Util.ConvertColorToInt("#555555"));
		// 将应用名加入到底部视图
		layoutBCenter.addView(tvName);

		// 如果简介为空的话就不显示简介
		if (!TextUtils.isEmpty(about)) {
			// 简介
			TextView tvRemark = new TextView(context);
			tvRemark.setText(about);
			// 字体大小14dip
			tvRemark.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
			tvRemark.setTextColor(Util.ConvertColorToInt("#888888"));
			// 将简介加入底部视图
			layoutBCenter.addView(tvRemark);
		}
		// 将底部中间视图加入底部视图
		layoutBottom.addView(layoutBCenter);
		MyButton skipButton = new MyButton(context);
		final long entryTime=System.currentTimeMillis();
		skipButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				WindowUtil.getModel(context).hidePopupWindow();
				
				if(v.getTag()==null){
					return;
				}
				  AnalysisBuilder ab=AnalysisBuilder.create()
			        		.putComeTime(""+entryTime).putExitTime().
			        		putOpen(OpenManner.DEFAULT)
			        		.putImg(advert==null?"":advert.getImgfile(AdType.STARTUP)).putImgUrl(advert==null?"":advert.getApkfile())
			        		.putStayTime(""+(System.currentTimeMillis()-entryTime)/1000);
				
				int t=(Integer) v.getTag();
				if(showSecond==t){//自动完成
					ab.putState(DownLoadState.FINSH).putIsBreak(IsBreak.NOTSKIP).putClick(Click.FINSH);
				}else{//点击跳过广告
					ab.putState(DownLoadState.ENTER).putIsBreak(IsBreak.SKIP).putClick(Click.WAIT);
				}
	        Analysis.getBrowserAnalysis().analysisStartUp(AnalysisConsts.SCENE_STARTING, "", "",ab);
			}
		});
		//启动图开始
		 AnalysisBuilder ab=AnalysisBuilder.create()
	        		.putComeTime(""+entryTime).putExitTime().
	        		putOpen(OpenManner.DEFAULT)
	        		.putImg(advert==null?"":advert.getImgfile(AdType.STARTUP)).putImgUrl(advert==null?"":advert.getApkfile())
	        		.putStayTime(""+(System.currentTimeMillis()-entryTime)/1000).putIsBreak(IsBreak.NOTSKIP)
	        		.putState(DownLoadState.CLICK).putIsBreak(IsBreak.NOTSKIP).putClick(Click.CLICK);
         Analysis.getBrowserAnalysis().analysisStartUp(AnalysisConsts.SCENE_STARTING, "", "",ab);
		
		
		// 设置按钮宽度跟高度
		blp = new LinearLayout.LayoutParams(Util.dip2px(context, 80),
				Util.dip2px(context, 45));
		skipButton.setLayoutParams(blp);
		// 去掉系统默认的padding
		skipButton.setPadding(0, 0, 0, 0);
		// 字体大小14dip
		skipButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
		// 设置按钮字体颜色
		skipButton.setTextColor(Util.ConvertColorToInt("#555555"));
		// 默认图片
		Drawable drawable1 = Util.getAssetsDrawable(context,
				"img/btn_white.9.png");
		// 按下去的图片
		Drawable drawable2 = Util.getAssetsDrawable(context,
				"img/btn_white_p.9.png");
		// 设置按钮背景Selector
		skipButton.setBackground(drawable1, drawable2);
		// 将按钮加入底部视图中
		layoutBottom.addView(skipButton);
		// 将底部视图加入到整体视图中
		layout.addView(layoutBottom);
		new TimeThread(showSecond, new MyHandler(context, onStartUpDimissListener,
				skipButton,showSecond)).start();
		return layout;
	}

	@SuppressLint("HandlerLeak")
	private static class MyHandler extends Handler {
		Context context;
		OnStartUpDimissListener onStartUpDimissListener;
		MyButton skipButton = null;
		int showSecond;

		public MyHandler(Context context, OnStartUpDimissListener onStartUpDimissListener,
				MyButton skipButton,int showSecond) {
			this.context = context;
			this.onStartUpDimissListener = onStartUpDimissListener;
			this.skipButton = skipButton;
			this.showSecond=showSecond;
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				if (skipButton != null) {
					String langu = AppInfoUtil.getLanguage(context);
					String text = (langu.equals("cn") ? "跳过" : "skip") + "("
							+ msg.obj + ")";
					skipButton.setText(text);
					skipButton.setTag(showSecond-(Integer)msg.obj);
				}
				break;
			case 2:
				if (onStartUpDimissListener != null) {
					onStartUpDimissListener.startUpDimiss();
				}
				skipButton.setTag(showSecond);
				skipButton.onClick();
				break;
			}
			super.handleMessage(msg);
		}

	};

	private static class TimeThread extends Thread {
		int showSecond = 3;// 默认倒计时三秒
		int maxSecond = 5;// 最多停留5秒
		Handler handler;

		private TimeThread(int showSecond, Handler handler) {
			if (showSecond <= maxSecond) {
				this.showSecond = showSecond;
			} else {
				this.showSecond = maxSecond;
			}
			this.handler = handler;
		}

		public void run() {
			while (true) {
				if (handler != null) {
					Message mess = new Message();
					mess.obj = showSecond;
					mess.what = showSecond == 0 ? 2 : 1;
					handler.sendMessage(mess);
				}
				if (showSecond == 0)
					break;
				--showSecond;
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	

	/**
	 * 获取推荐产品视图
	 * 
	 * @param list
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static View getRecommendView(final Context context,List<Products> list, String mess,final OnProductDLListener touchListener,OnClickListener clickListener) {
		RelativeLayout layout = new RelativeLayout(context) {

			@Override
			public boolean dispatchKeyEvent(KeyEvent event) {
				if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
					WindowUtil.getModel(context).hidePopupWindow();
				}
				return super.dispatchKeyEvent(event);
			}

		};
		layout.setOnClickListener(clickListener);
		layout.setLayoutParams(new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.MATCH_PARENT,
				RelativeLayout.LayoutParams.MATCH_PARENT));
		LinearLayout bottomLayout = new LinearLayout(context);
		bottomLayout.setBackgroundDrawable(Util.getAssetsDrawable(context,
				"img/bottom_bg.9.png"));
		RelativeLayout.LayoutParams lpara = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		lpara.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		bottomLayout.setLayoutParams(lpara);
		bottomLayout.setOrientation(LinearLayout.VERTICAL);

		// 卸载说明
		TextView tv = new TextView(context);
		tv.setText(mess);
		tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
		tv.setGravity(Gravity.CENTER);
		int padding = Util.dip2px(context, 10);
		tv.setTextColor(Color.RED);
		tv.setPadding(padding, padding * 2, padding, padding);
		bottomLayout.addView(tv);

		// 分割视图
		LinearLayout layout_split = new LinearLayout(context);
		layout_split.setOrientation(LinearLayout.HORIZONTAL);
		layout_split.setGravity(Gravity.CENTER);

		// 第一条横线
		TextView tv_line1 = new TextView(context);
		tv_line1.setBackgroundColor(Util.ConvertColorToInt("#999999"));
		LinearLayout.LayoutParams lp1_line1 = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT, 1);
		lp1_line1.weight = 1;
		tv_line1.setLayoutParams(lp1_line1);
		layout_split.addView(tv_line1);

		// 推荐说明
		TextView tv1 = new TextView(context);
		tv1.setText("Recommended Applications");
		tv1.setTextColor(Util.ConvertColorToInt("#999999"));
		padding = Util.dip2px(context, 5);
		tv1.setPadding(padding, 0, padding, 0);
		LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		tv1.setLayoutParams(lp1);
		layout_split.addView(tv1);

		// 第二条横线
		TextView tv_line2 = new TextView(context);
		tv_line2.setBackgroundColor(Util.ConvertColorToInt("#cccccc"));
		LinearLayout.LayoutParams lp1_line2 = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT, 1);
		lp1_line2.weight = 1;
		tv_line2.setLayoutParams(lp1_line2);
		layout_split.addView(tv_line2);

		bottomLayout.addView(layout_split);

		// 产品视图
		padding = Util.dip2px(context, 10);

		// 每行展示产品数
		int count = 5;
		// 计算行数
		int line = list.size() % count == 0 ? list.size() / count : list.size()
				/ count + 1;
		// 计算图片的宽度
		int width = (ScreenUtils.getScreenWidth(context) - padding
				* (count + 1))
				/ count;
		// 创建视图
		for (int i = 0; i < line; i++) {
			LinearLayout layout_pro = new LinearLayout(context);
			LinearLayout.LayoutParams lpiv = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT);
			lpiv.topMargin = padding;
			layout_pro.setLayoutParams(lpiv);
			layout_pro.setOrientation(LinearLayout.HORIZONTAL);
			layout_pro.setGravity(Gravity.CENTER_VERTICAL);

			for (int j = i * count; j < (i == line - 1 ? list.size() : count
					* (i + 1)); j++) {
				final Products pro = list.get(j);

				LinearLayout layout_item = new LinearLayout(context);
				LinearLayout.LayoutParams itemlp = new LinearLayout.LayoutParams(
						width, LinearLayout.LayoutParams.WRAP_CONTENT);
				itemlp.leftMargin = padding;
				layout_item.setLayoutParams(itemlp);
				layout_item.setOrientation(LinearLayout.VERTICAL);

				layout_item.setOnTouchListener(new OnTouchListener() {

					@Override
					public boolean onTouch(View v, MotionEvent event) {
						if(touchListener!=null){
							touchListener.onDownLoad(pro);
						}
						return false;
					}
				});

				final ImageView iv = new ImageView(context);
				DLImage image = new DLImage(null);
				image.setOnDLImageSuccessListener(new OnDLImageSuccessListener() {

					@Override
					public void success(Drawable drawable) {
						if (drawable != null) {
							iv.setBackgroundDrawable(drawable);
						}
					}
				});
				image.start(pro, AdType.RECOMMENDS);
				lpiv = new LinearLayout.LayoutParams(width, width);
				lpiv.bottomMargin = Util.dip2px(context, 3);
				iv.setLayoutParams(lpiv);
				layout_item.addView(iv);

				TextView tv_name = new TextView(context);
				tv_name.setText(pro.getName());
				tv_name.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
				tv_name.setGravity(Gravity.CENTER);
				tv_name.setSingleLine();
				tv_name.setTextColor(Util.ConvertColorToInt("#555555"));
				layout_item.addView(tv_name);

				layout_pro.addView(layout_item);
			}
			bottomLayout.addView(layout_pro);
		}
		bottomLayout.setPadding(0, 0, 0, padding);
		layout.addView(bottomLayout);

		return layout;
	}
}
